import { useCallback, useState } from 'react';
import { useRequest } from 'ahooks';
import { apiGetArticleCategories } from '@/api/article.api';
import { ke } from '@/plugins/ke';
import { Category } from '@/pages/article/category';

export default () => {
  const [data, setData] = useState<Category[]>([]);

  const loadData = useCallback(() => {
    useRequest(apiGetArticleCategories, {
      onSuccess: data => {
        setData(
          ke.array().tree(
            data.list.map((item: any) => {
              return {
                ...item,
                value: item.id,
                title: item.name,
              };
            }),
            'id',
            'pid',
          ),
        );
      },
    });
  }, []);

  return {
    data,
    load: loadData,
    update: useCallback(newData => {
      setData(newData);
    }, []),
  };
};
